package kuzha.runtime;

import java.util.Map;

import kuzha.KuzhaObject;

public class StructPattern extends CasePattern {
	public final String name;
	public final CasePattern[] pats;
	public final CasePattern tail;
	
	private StructPattern(String name, CasePattern[] pats, CasePattern tail) {
		if (name == null || pats == null)
			throw new IllegalArgumentException();
		this.name = name;
		this.pats = (CasePattern[]) pats.clone();
		this.tail = tail;
	}
	
	@Override
	public boolean match(KuzhaObject value, Map<String, KuzhaObject> vars) {
		if (value instanceof KzStruct) {
			KzStruct struct = (KzStruct) value;
			if (name.equals(struct.getName())) {
				if (pats.length == struct.size() || (tail != null && pats.length < struct.size())) {
					for (int i = 0; i < pats.length; i++) {
						if (!pats[i].match(struct.get(i), vars)) {
							return false;
						}
					}
					if (tail != null) {
						if (!tail.match(struct.slice(pats.length), vars)) {
							return false;
						}
					}
					return true;
				}
			}
		}
		return false;
	}
	
	public static StructPattern valueOf(String name, CasePattern[] pats, CasePattern tail) {
		return new StructPattern(name, pats, tail);
	}
}
